document.addEventListener("DOMContentLoaded", function () {
    // 获取当前激活的标签页
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function (tabs) {
        const tab = tabs[0];
        const favicon = document.getElementById("favicon");
        const title = document.getElementById("title");
        const titleInput = document.getElementById("titleInput");
        const urlInput = document.getElementById("urlInput");
        // 获取当前页面的Favicon
        favicon.src = tab.favIconUrl;
        // 显示当前页面的标题和网址
        title.textContent = tab.title;
        titleInput.value = tab.title;
        urlInput.value = tab.url;

        document.getElementById("postButton").addEventListener("click", function () {
            const text = titleInput.value;
            const uri = urlInput.value;
            const icon = tab.favIconUrl;
            let pagesData = getStorageNavData()
            let size = pagesData.length
            if (size > 0) {
                let insertItems = pagesData[size - 1].items;
                if (insertItems.length < getMaxItem()) {
                    insertItems.push({
                        id: getNewId(),
                        text: text,
                        uri: uri,
                        icon: icon
                    })
                } else {
                    let item = {
                        pageId: "page" + getNewPageId(),
                        items: [{
                            id: getNewId(),
                            text: text,
                            uri: uri,
                            icon: icon
                        }],
                    }
                    pagesData.push(item)
                }
            } else {
                pagesData = [{
                    pageId: "page" + getNewPageId(),
                    items: [{
                        id: getNewId(),
                        text: text,
                        uri: uri,
                        icon: icon
                    }],
                }];
            }
            // 保存数据
            saveStorageNavData(pagesData)
            sendMessage({data: "refresh"})
            window.close()
        });
    });
});